<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="vue.js"></script>
</head>

<body>
    <!-- 相对时间转换  -->
    <div id="app">
        <p v-relative="time"></p>
    </div>
    <script>
        class Time {
            static getFormatTime(time) {
                // 获取当前时间  毫秒
                let now = new Date().getTime();
                //console.log(now);
                //计算秒数
                time = parseInt((now - time) / 1000);
                if (time < 60) {
                    return time + "秒前";
                }
                // 获得分钟数
                time = parseInt(time / 60);
                if (time < 60) {
                    return time + "分钟前";
                }
                //获得小时数
                time = parseInt(time / 60);
                if (time < 24) {
                    return time + "小时前";
                }
                //获得天数
                time = parseInt(time / 24);
                if (time < 365) {
                    return time + "天前";
                }
                //计算年数
                time = parseInt(time / 365);
                return time + "年前";
            }
        }
        //定义一个全局指令
        Vue.directive('relative', {
            inserted: function(el, binding) {
                console.log(el);
                // 得到标签上的数据，调用函数将结果设置为文本
                el.innerHTML = Time.getFormatTime(binding.value)

                // 设置定时器,定时刷新结果 __原数据
                el.__timeout__ = setInterval(() => {
                    el.innerHTML = Time.getFormatTime(binding.value)
                }, 6000)
            },
            unbind: function(el) {
                clearInterval(el.innerHTML)
                delete el.__timeout__
            }
        });
        //创建Vue对象
        let vue = new Vue({
            el: "#app",
            data: {
                //发表朋友圈的时间
                time: 1637237542545
            }
        });
    </script>
</body>

</html>